package com.ceo.common.config;

import cn.hutool.core.util.StrUtil;
import com.ceo.common.utils.CommonContextUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author uto_dev_008
 * @desc
 * @since 2023/6/2 9:30
 * Copyright (c)  All rights reserved
 */
@Configuration
public class YangWebMvcConfig  implements WebMvcConfigurer {
    @Value("${spring.web.resources.static-locations}")
    private String staticLocations;

    /**
     * 添加拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<HandlerInterceptor> interceptors = CommonContextUtil.getBeanListOfType(HandlerInterceptor.class);
        String[] rules = new String[]{
                "/v2/api-docs",
                "/swagger-resources/configuration/ui",
                "/swagger-resources",
                "/swagger-resources/configuration/security",
                "/swagger-ui.html",
                "/auth/user/login",
                "/doc.html",
                "/webjars/**",
                "/auc/user/login",
                "/unauthorized/**"
        };
        if (!CollectionUtils.isEmpty(interceptors)) {
            interceptors.forEach(item -> registry.addInterceptor(item).excludePathPatterns(rules));
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (StrUtil.isEmpty(this.staticLocations)) {
            this.staticLocations = "classpath:/META-INF/resources/,classpath:/META-INF/resources/webjars/,classpath:/static/";
        } else if (StrUtil.isNotEmpty(this.staticLocations) && this.staticLocations.indexOf("classpath:/static/") == -1) {
            this.staticLocations = this.staticLocations + ",classpath:/META-INF/resources/,classpath:/META-INF/resources/webjars/,classpath:/static/";
            this.staticLocations = this.staticLocations.replace(",,", ",");
        }
        registry.addResourceHandler(new String[]{"/**"}).addResourceLocations(this.staticLocations.split(","));
    }
}
